package com.webserver.http;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/*
* 请求对象
* 该类的每一个实例用于表示浏览器发送过来的一个请求内容
* 每个请求由三部分构成：
* 请求行，消息头，消息正文
* */
public class HttpRequest {
    //请求行相关信息
    private String method;//请求方式
    private String url;//抽象路径
    private String protocol;//协议版本

    private Map<String,String> headers = new HashMap<>();

    //消息头相关信息
    //Key：消息头的名字  value:消息头对应的值
    private Socket socket;
    public HttpRequest(Socket socket) throws IOException{
        this.socket = socket;
        //1.1：解析请求行
        parseRequestLine();
        //1.2：解析消息头
        parseHeaders();
        //1.3：解析消息正文
        parseContent();
    }
    private void parseRequestLine() throws IOException {
        String line = readLine();//读取一个文本行
        System.out.println(line);
        //将请求行内容解析并复制给对应的method url protocol
        String []data = line.split("\\s");
        method = data[0];
        url = data[1];
        protocol = data[2];
        System.out.println("请求方式为："+method);
        System.out.println("抽象路径为"+url);
        System.out.println("协议版本"+protocol);
    }
    private void parseHeaders()throws IOException{
        String line;
        String []data;
        while(!(line = readLine()).isEmpty()){
            System.out.println("消息头"+line);
            data = line.split("\\s");
            headers.put(data[0],data[1]);
        }
        System.out.println("headers"+headers);
    }
    private void parseContent()throws IOException{

    }
    private String readLine() throws IOException{
        /*
        * 调用同一个socket对象的getInputStream()或getOutputStream()
        * 方法若干次，返回的始终是同一个流
        * */
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
         int d;
         char pre = 'a',cur = 'a';
         while((d = in.read())!=-1){
             cur = (char)d;
             if(pre == 13 && cur == 10){
                 break;
             }
             builder.append(cur);
             pre = cur;
         }
         return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }
}